<?php

declare(strict_types=1);

namespace App\Job;

use App\Log;
use App\Constants\RedisKey;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Suyar\ClickHouse\Client;
use Hyperf\AsyncQueue\Job;

class PullCharacterJob extends Job
{
    public $params;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     */
    protected int $maxAttempts = 2;

    public function __construct($params)
    {
        // 这里最好是普通数据，不要使用携带 IO 的对象，比如 PDO 对象
        $this->params = $params;
    }

    public function handle()
    {
        dump('===========开始拉取===========');
        try {
            //dump($this->params);
            $uid = $this->params['uid'];
            $data_version = $this->params['data_version'];
            $user_character_key = $this->params['user_character_key'];
            // Job里面不能注入
            $client = new Client(config('clickhouse')['default']);
            // 测试链接
            $ping = $client->ping(true);
            if (!$ping) {
                Log::custom('PullCharacter', ['result'=>'ping clickhouse false', 'uid'=>$uid]);
                return false;
            }
            //查询clickhouse
            $params = $client->newQuery('SELECT * FROM user WHERE uid={uid:Integer}');
            $params->setBindings(['uid' => $uid, 'version' => $data_version]);
            $response = $client->send($params);
            if ($response->rows > 0) {
                // 把数据写入缓存
                $data = $response->data[0] ?? []; // 取第一条 (结果应该只有一条)
                redis()->set($user_character_key, json_encode($data));
                redis()->expire($user_character_key,RedisKey::EXPIRE_24H);
            }
            // 记录今天是否拉取过
            $already_pull_key = RedisKey::getKey(RedisKey::ALREADY_PULL_CHARACTER, Carbon::now()->startOfDay()->timestamp, $data_version, $uid);
            redis()->set($already_pull_key, 1);
            redis()->expire($already_pull_key,RedisKey::EXPIRE_24H);
            Log::custom('PullCharacter', $data ?? ['uid'=>$uid]);
        } catch (\Exception $exception) {
            dump('任务出错: ' . $exception->getFile());
            dump('任务出错: ' . $exception->getLine());
            dump('任务出错: ' . $exception->getMessage());
            Log::custom('PullCharacter', ['result'=>'pull clickhouse false', 'uid'=>$this->params['uid']]);
        }
    }
}